// pages/chargingPile/chargingPile/chargingPile.js

const amapFile = require('../../utils/amap-wx');

import { 
  amapWebKey,
  amapWeChatKey
} from '../../utils/ipconfig';

import { amapApi } from '../../api/amap';

import { amapRequest } from '../../utils/request';

Page({
  data: {
    latitude: null,
    longitude: null,
    isShow: false,
    markers: [],
    points: [],
    inputValue: '',
    location: '',
    name:'',
    address: '',
    adcode: '',
    citycode: ''
  },

  // 导航
  async bindNavigationTap() {
    if(this.data.inputValue == '') {
      return wx.showToast({
        icon: 'none',
        title: '请输入导航地址'
      })
    }
    const res = {
      data: {
        key: amapWebKey,
        address: this.data.inputValue
      },
      url: amapApi.geocode()
    }
    const returnValue = await amapRequest(res);
    const latitude = Number(returnValue[0].location.split(',')[0]);
    const longitude = Number(returnValue[0].location.split(',')[1]);
    wx.openLocation({
      latitude,
      longitude,
      scale: 15,
      name: this.data.inputValue,
      address: returnValue[0].formatted_address,
    })
  },

  // 名称输入框完成，失去交点事件
  async bindInput(e) {
    // 开始加载等待
    wx.showLoading({
      mask: true,
      title: '地图加载中'
    })
    /*
      *  举例输入框输入'曹杨', 这个时候高德地图会返回他属于的城市+区+地域全称是'上海市普陀区曹杨', 
      *  和一个loaction 经纬度，这时候比较模糊，不精准，我会拿出全称"上海市普陀区曹杨" 再去查询一次，
      *  这时候获得更加精准的经纬度，也就是说，输入框，背后会有2次查询经纬度查询，
      *  因为用户可能输入的跟我一样，是附近的地理位置名称，比较模糊。
      *  这里其实我就是将用户输入的内容，补足城市区域，这样子方便精准定位。
      *  如果直接用用户输入内容的经纬度，会有点偏差。。
    */ 
    // 输入框内容查询
    const res = {
      data: {
        key: amapWebKey,
        address: e.detail.value
      },
      url: amapApi.geocode()
    }
    const returnValue = await amapRequest(res);
    // 查询补足信息
    const res2 = {
      data: {
        key: amapWebKey,
        address: returnValue[0].formatted_address
      },
      url: amapApi.geocode()
    }
    const returnValue2 = await amapRequest(res2);
    this.setData({
      inputValue: e.detail.value,
      adcode: returnValue2[0].adcode,
      citycode: returnValue2[0].citycode,
      location: returnValue2[0].location
    })
    // 地理编码
    await this.getRegeo();
    // 结束loading
    wx.hideLoading();
  },

  //通过关键词获取附近的点，只取前十个，同时保证十个点在地图中显示
  getAround() {
    const that = this;
    const myAmapFun = new amapFile.AMapWX({ key: amapWeChatKey });
    myAmapFun.getPoiAround({
      // 默认第一项选中icon
      querykeywords: '公园',
      adcode: that.data.adcode,
      citycode: that.data.citycode,
      location: that.data.location,
      success(data) {
        if (data.markers) {
          let markers = [], points = [];
          for (let value of data.markers) {
            if (value.id > 9) break;
            if(value.id == 0){
              that.setData({
                name: value.name,
                address: value.address,
                isShow: true
              })
            }
            markers.push({
              id: value.id,
              latitude: value.latitude,
              longitude: value.longitude,
              title: value.name,
              iconPath: value.iconPath,
              width: 32,
              height: 32,
              anchor: { x: .5, y: 1 },
              label: {
                content: value.name,
                color: '#666666',
                fontSize: 12,
                borderRadius: 5,
                bgColor: '#fff',
                padding: 3,
                x: 0,
                y: -50,
                textAlign: 'center'
              }
            });
            points.push({
              latitude: value.latitude,
              longitude: value.longitude
            })
          }
          that.setData({
            markers: markers,
            points: points
          })
        }
      },
      fail: function (info) {
        wx.navigateTo({ 
          url: `/pages/error/error/error?successCode=${info}&type=高德地图`
        })
      }
    })
  },

  // 地理编码
  async getRegeo() {
    const that = this;
    const myAmapFun = new amapFile.AMapWX({
      key: amapWeChatKey
    });
    myAmapFun.getRegeo({
      location: that.data.location,
      success: async(res) => {
        that.setData({
          adcode: res[0].regeocodeData.addressComponent.adcode,
          citycode: res[0].regeocodeData.addressComponent.citycode
        });
        await that.getAround();
      }
    });
  },

  // 获取当前定位位置为地图的中心坐标
  getLocation() {
    const that = this;
    // 开始加载等待
    wx.showLoading({
      mask: true,
      title: '地图加载中'
    })
    wx.getLocation({
      async success(data) {        
        if (data) {
          that.setData({
            latitude: data.latitude,
            longitude: data.longitude,
            location: data.longitude + ',' + data.latitude,
            markers:[{
              id:0,
              latitude: data.latitude,
              longitude: data.longitude,
              width: 32,
              height: 32
            }]
          });
          await that.getRegeo();
          // 结束loading
          wx.hideLoading();
        }
      }
    });
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getLocation();    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
   
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
});